package com.augmentum.oes.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.augmentum.oes.Constants;
import com.augmentum.oes.exception.ParameterException;
import com.augmentum.oes.exception.ServiceException;
import com.augmentum.oes.model.Exam;
import com.augmentum.oes.model.Pagination;
import com.augmentum.oes.model.SortFieldEnum;
import com.augmentum.oes.model.SortStatusEnum;
import com.augmentum.oes.service.ExamService;
import com.augmentum.oes.service.QuestionBackupService;
import com.augmentum.oes.util.PropertyUtil;
import com.augmentum.oes.util.StringUtil;

@Controller
@RequestMapping(value = Constants.APP_URL_PREFIX)
public class ExamController extends BaseController {

    private static final String EXAM_MANAGE_JSP = "exam/exammanagement";
    private static final String RIGHT_PAGE_NUMBER = "Please input a right page number!";
    private static final String CURRENT_PAGE = "1";
    private static final String CREATE_EXAM_JSP = "exam/create-exam";

    private static final String EXAM_EDIT_JSP = "exam/edit-exam";

    private static final String EXAMOBJECT = "examobject";
    private static final String CURRENTPAGE = "examCurrentPage";
    private static final String SORTSTATUS = "examSortstatus";
    private static final String PAGESIZE = "examPageSize";
    private static final String PAGNATION = "examPagnation";
    private static final String PAGINATION_PAGESIZE = "pagination.pageSize";
    private static final String KEYWORD = "examKeyWord";
    private static final String CREATE_SUCCESS = "Create success!";
    private static final String SORT_FIELD = "sortfield";
    private static final String TO_EXAM_EDIT = "toexamedit";
    private static final Object UPDATE_SUCCESS = "Update success";
    private static final String TO_EXAM_LIST = "toexamlist";
    private static final Object DELETE_SUCCESS = "Delete success!";
    private static final String ID = "id";
    private static final String TOTAL_QUESTION_MSG = "Sorry,the question is not enough in the system!";

    @Resource
    private ExamService examService;

    @Resource
    private QuestionBackupService questionBackService;

    public ExamController() {
        super();
    }

    @RequestMapping(value = { "toexamlist" })
    public ModelAndView toExamList(@RequestParam(value = "currentPage", required = false) String currentPage,
            @RequestParam(value = "sort", required = false, defaultValue = "ASC") String sort,
            @RequestParam(value = "exampageSize", required = false) String examPageSize,
            @RequestParam(value = "sortfield", required = false, defaultValue = "ID") String sortField,
            @RequestParam(value = "keyWord", required = false) String keyWord, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        this.addSession(KEYWORD, keyWord);
        this.removeSession(EXAMOBJECT);
        SortFieldEnum field = null;
        try {
            field = SortFieldEnum.valueOf(sortField);
        } catch (Exception e) {
            field = SortFieldEnum.valueOf("ID");
        }
        SortStatusEnum sortStatus = null;
        try {
            sortStatus = SortStatusEnum.valueOf(sort);
        } catch (Exception e) {
            sortStatus = SortStatusEnum.valueOf("ASC");
        }
        this.addSession(SORTSTATUS, sortStatus.toString());
        this.addSession(SORT_FIELD, field);
        if (!StringUtil.isEmpty(currentPage) || !StringUtil.isEmpty(examPageSize)) {
            this.addSession(CURRENTPAGE, currentPage);
            this.addSession(PAGESIZE, examPageSize);
        }
        if (StringUtil.isEmpty(currentPage)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(CURRENTPAGE))) {
                currentPage = (String) session.getAttribute(CURRENTPAGE);
            } else {
                currentPage = CURRENT_PAGE;
            }
        }
        if (StringUtil.isEmpty(examPageSize)) {
            if (!StringUtil.isEmpty((String) session.getAttribute(PAGESIZE))) {
                examPageSize = (String) session.getAttribute(PAGESIZE);
            } else {
                examPageSize = PropertyUtil.getProperties(PAGINATION_PAGESIZE);
            }
        }
        Pagination pagination = new Pagination();
        try {
            pagination.setCurrentPage(Integer.parseInt(currentPage));
            pagination.setPageSize(Integer.parseInt(examPageSize));
        } catch (NumberFormatException e) {
            this.addSession(Constants.TIP_MESSAGE, RIGHT_PAGE_NUMBER);
            modelAndView.setViewName(EXAM_MANAGE_JSP);
        }
        try {
            this.addSession(Constants.EXAM_VIEW_LIST,
                    examService.getList(pagination, sortStatus, field.toString(), keyWord));
            this.addSession(PAGNATION, pagination);
            modelAndView.setViewName(EXAM_MANAGE_JSP);
        } catch (ServiceException e) {
            this.addSession(Constants.TIP_MESSAGE, e.getErrorMessage());
            modelAndView.setViewName(EXAM_MANAGE_JSP);
        }
        return modelAndView;
    }

    @RequestMapping(value = { "tocreateexam" })
    public ModelAndView toCreateExam() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(CREATE_EXAM_JSP);
        return modelAndView;
    }

    @RequestMapping(value = { "createexam" }, method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("exam") Exam exam) throws ParameterException {
        ModelAndView modelAndView = new ModelAndView();
        exam.setCreator(this.getUser());
        String msg = null;
        msg = examService.saveExam(exam);
        if (StringUtil.isEmpty(msg)) {
            questionBackService.savePaper(exam);
            this.addSession(Constants._SUCCESS, CREATE_SUCCESS);
            modelAndView.setViewName(CREATE_EXAM_JSP);
        } else {
            this.addSession(Constants.TIP_MESSAGE, msg);
            modelAndView.setViewName(CREATE_EXAM_JSP);
        }
        return modelAndView;
    }

    @RequestMapping(value = { "examdetail" })
    @ResponseBody
    public List<Exam> viewDetail(@RequestParam(value = "id") int id) {
        List<Exam> list = examService.getQuestionByExamId(id);
        return list;
    }

    @RequestMapping(value = { "toexamedit" })
    public ModelAndView toExamEdit(@RequestParam(value = "id") int id) {
        ModelAndView modelAndView = new ModelAndView();
        this.addSession(EXAMOBJECT, examService.getById(id));
        modelAndView.setViewName(EXAM_EDIT_JSP);
        return modelAndView;
    }

    @RequestMapping(value = { "updateexam" })
    public ModelAndView update(@ModelAttribute("exam") Exam exam, RedirectAttributes redirectAttributes) {
        ModelAndView modelAndView = new ModelAndView();
        exam.setTotalScore(exam.getQuestionPoints() * exam.getQuestionQuantity());
        String msg = examService.updateExam(exam);
        if (StringUtil.isEmpty(msg)) {
            modelAndView.setView(this.getRedirectView(TO_EXAM_EDIT));
            redirectAttributes.addFlashAttribute(Constants.SUCCESS_MSG, UPDATE_SUCCESS);
            redirectAttributes.addAttribute(ID, exam.getId());
        } else {
            redirectAttributes.addFlashAttribute(Constants.SUCCESS_MSG, TOTAL_QUESTION_MSG);
            redirectAttributes.addAttribute(ID, exam.getId());
        }
        return modelAndView;
    }

    @RequestMapping(value = "deleteexam")
    public ModelAndView deleteexam(@RequestParam("checkboxOneInput") String[] idStr,
            RedirectAttributes redirectAttributes) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            examService.dropById(idStr);
            redirectAttributes.addFlashAttribute(Constants.TIP_MESSAGE, DELETE_SUCCESS);
        } catch (ParameterException e) {
            redirectAttributes.addFlashAttribute(Constants.ERROR_MESSAGE, e.getErrorMessage());
        }
        modelAndView.setView(this.getRedirectView(TO_EXAM_LIST));
        return modelAndView;
    }

    @RequestMapping(value = "searchbydate")
    public ModelAndView searchByDate(@RequestParam("start") String start, @RequestParam("end") String end) {
        ModelAndView modelAndView = new ModelAndView();
        List<Exam> list = examService.searchByDate(start, end);
        this.addSession(Constants.EXAM_VIEW_LIST, list);
        modelAndView.setViewName(EXAM_MANAGE_JSP);
        return modelAndView;
    }
}
